import { download_file, serialize } from 'util';

import * as Util from "utils";

export default {
  data() {
    return {
      cacheParams: {
        inputParams: {},
        pageParams: {},
        sortParams: {}
      }
    }
  },
  methods: {
    // 私有方法，不建议在组件中使用
    _loadData({
      inputParams = {},
      pageParams = {},
      sortParams = {},
    }) {
      const finalParams = Object.assign({}, inputParams, pageParams, sortParams);
      console.log('Ajaxing...request params is', finalParams);
      this.getData(finalParams);
    },
    // 用于输入参数后按下Enter或点击搜索按钮,
    // 注意如果使用enter等方式触发时，默认回调函数参数为 KeyboardEvent，
    // 因此调用方式须为 @enter="searchByInput()" 或者 @enter="searchByInput({...})"
    searchByInput(newInputParams) {
      this.cacheParams.inputParams = newInputParams || this.getInputParams && this.getInputParams();
      this._loadData({
        inputParams: this.cacheParams.inputParams,
        pageParams: { page: 1 }
      });
    },
    // 用于先验证输入参数，验证通过后再进行搜索
    // 请在form组件加上rules和ref: <v-form :rules="rules" ref="form"> 
    searchByInputValidate(newInputParams) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.searchByInput(newInputParams);
        }
      });
    },
    // 用于分页搜索
    searchByPage(newPageParams) {
      this._loadData({
        inputParams: this.cacheParams.inputParams,
        pageParams: newPageParams,
        sortParams: this.cacheParams.sortParams,
      });
    },
    // 用于排序搜索
    searchBySort(newSortParams) {
      this.cacheParams.sortParams = newSortParams;
      this._loadData({
        inputParams: this.cacheParams.inputParams,
        pageParams: { page: 1 },
        sortParams: newSortParams
      });
    },
    // 用于导出文件
    exportFile(shortUrl, extraParams={}) {
      const finalParams = Object.assign({}, this.cacheParams.inputParams, this.cacheParams.sortParams, extraParams);
      const finalUrl = URLConfig(shortUrl) + Util.serialize(finalParams);
      console.log('Downloading...request params is', finalParams);
      Util.download_file(finalUrl);
    }
  },
  created() {
    this.listen && this.listen();
  }
}